// 记录上次首页的连接数组
let lastSrcs
const scriptReg = /\<script.*src=["'](?<src>[^"']+)/gm

// 请求首页，获取script中的src,然后保存，定时获取然后跟上一次的进行对比
async function extractNewScript() {
    const html = await fetch('/?_timestamp=' + Data.now()).then(res => res.text())
    scriptReg.lastIndex = 0
    let result = []
    let match
    while((match = scriptReg.exec(html))) {
        result.push(match.groups.src)
    }
    return result
}

async function needUpdate() {
    const newScripts = await extractNewScript()
    // 没有值，代表首次进入页面，进行第一次赋值
    if (!lastSrcs) {
        lastSrcs = newScripts
        return false
    }
    // let result = false
    if (lastSrcs.length != newScripts.length) {
        lastSrcs = newScripts
        return true
        // result = true
    }
    for(let i = 0; i < lastSrcs; i++) {
        if (lastSrcs[i] !== newScripts[i]) {
            lastSrcs = newScripts
            return true
            // result = true
            // break
        }
    }
    // lastSrcs = newScripts
    // return result
}

const DURATION = 2000
function autoRefesh() {
    setTimeout(async () => {
        const willUpdate = await needUpdate()
        if (willUpdate) {
            const result = confirm('页面有更新，点击确定刷新页面')
            if (result) {
                window.location.reload()
            }
        } else {
            autoRefesh()
        }
    }, DURATION)
}
autoRefesh()